package com.example.webdemo.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.UUID;

/**
 * @author zp
 * @version 1.0
 * @description: 工具库
 * @date 2023/8/14 21:39
 */
@Component
public class MyUtils {
    private static String uploadLocation;

    @Value("${upload.location}")
    public void setUploadLocation(String uploadLocation) {
        MyUtils.uploadLocation = uploadLocation;
    }

    public static boolean isFileExist(String fileUrl){
        String fileName = getImageNameByPath(fileUrl);
        System.out.println(uploadLocation + fileName);
        Path path = Paths.get(uploadLocation + fileName);
        return Files.exists(path);
    }

    public static String getSavePath() {
        // 这里需要注意的是ApplicationHome是属于SpringBoot的类
        // 获取项目下resources/static/img路径
        ApplicationHome applicationHome = new ApplicationHome(MyUtils.class);

        // 保存目录位置根据项目需求可随意更改
        return applicationHome.getDir().getParentFile()
                .getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\image";
    }

    /**
     * 从图片的文件路径中获取图片名字
     * @param path
     * @return
     */
    public static String getImageNameByPath(String path){
        String fName = path.trim();       //删除路径两侧多余空格
        return fName.substring(fName.lastIndexOf("/")+1);
    }


    public static String saveFile(MultipartFile file) {
        // 给文件重命名
        String fileName = UUID.randomUUID() + "." + Objects.requireNonNull(file.getContentType())
                .substring(file.getContentType().lastIndexOf("/") + 1);
        try {
            // 获取保存路径
            String path = getSavePath();
            File files = new File(path, fileName);
            File parentFile = files.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdir();
            }
            file.transferTo(files);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/static/image/"+fileName; // 返回重命名后的文件名
    }
    /**
     * @description: 删除图片
     * @author zp
     * @date: 2023/8/15 20:39
     * @param fileUrl
     */
    public static void deleteFile(String fileUrl) {
        String fileName = getImageNameByPath(fileUrl);
        String filePath = uploadLocation+fileName;
        System.out.println(filePath);
        Path path = Paths.get(filePath);
        try {
            Files.deleteIfExists(path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
